package com.xu.cloud.common.util;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 随机数工具类
 *
 * @author xuguan
 * @since 2023/9/9
 */
public class RandomUtil {
    public static String genRandomNum(int digit) {
        return genRangeRandomNum(digit, 0, 9);
    }

    public static String genRangeRandomNum(int digit, int min, int max) {
        if (digit < 0 || min < 0 || max < 0) {
            throw new IllegalArgumentException("位数、最小值、最大值都不能小于0");
        }
        StringBuilder sb = new StringBuilder(digit);
        for (int i = 0; i < digit; i++) {
            sb.append(ThreadLocalRandom.current().nextInt(min, max + 1));
        }
        return sb.toString();
    }

    public static byte[] genRandomBytes(int digit) {
        if (digit < 0) {
            throw new IllegalArgumentException("位数不能小于0");
        }
        byte[] bytes = new byte[digit];
        try {
            SecureRandom.getInstanceStrong().nextBytes(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return bytes;
    }

    public static String randomUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
